require(["config"],function(){
	require(["jquery","template","xmcarousel","cookie","fly","header","footer"],function($,template,carousel,cookie){
		$(".slider").carousel({
			imgs : [
				{src : "/images/201712139113669765.jpg", href : "javascript:void(0)"},
				{src : "/images/201831315342987682 (1).jpg", href : "javascript:void(0)"}
			],
			width:738,
			height:353,
			isButton : false,
			idCircle : false
		});
		$.getJSON("http://rap2api.taobao.org/app/mock/25375/index",function(data){
			const html = template("list_temp",{list:data.res_body.data});
			$(".container_box").html(html);
		}).done(function(){
			$(".list").on("click",".add_to_carts",function(e){	
				const currProduct = {
					id : $(this).parents("li").find(".id").text(),
					img : $(this).parents("li").find(".img").find("img").attr("src"),
					desc : $(this).parents("li").find(".desc").text(),
					price : $(this).siblings('.currPrice').text().slice(1), 
					amount : 1
				};
				console.log(currProduct)
				$.cookie.json = true;
				const prods = $.cookie("products")|| [];	
				//判断当前选购商品是否已有购买
				const has = prods.some(function(curr){
					if(curr.id === currProduct.id){
						curr.amount++;
						return true;
					}
				})

				if(!has)//没有够买过则将当前选购商品对象添加到数组中保存
				prods.push(currProduct);
				//将数组重新保存到cookie
				$.cookie("products",prods,{expires:10,path:"/"});
				//添加购物车抛物线效果
				const end = $(".myCarts").offset();//抛物线终点
				const start = {left : e.pageX,top : e.pageY};//抛物线起点
				const flyer = $(`<img src="${currProduct.img}" style="width: 50px;height: 50px;z-index:999;">`);
				console.log(end, start, flyer)
				flyer.fly({
					start : {
						left : start.left,
						top : start.top - $(window).scrollTop()
					},
					end : {
						left : end.left,
						top : end.top - $(window).scrollTop()
					},
					onEnd : function(){//结束时，将抛物线运动元素删除
						this.destroy();
					}
				});


				//显示所有选购商品的总数量
				const totalAmount = prods.reduce(function(sum,curr){
					return sum += curr.amount;
				},0);
				$(".cart").text(totalAmount);
				$(".mycart").text(totalAmount);
				return false;
			});
		});



		$(".lianjie").hover(function(){
			$(".link_par").hide();
			$(".hezuo").css({"border":"none","color":"#969696"});
			$(".link_f").show();
			$(".lianjie").css({"borderBottom":"2px solid #ed1475","color":"#ed1475"});
		});
		$(".hezuo").hover(function(){
			$(".link_f").hide();
			$(".lianjie").css({"border":"none","color":"#969696"});
			$(".link_par").show();
			$(".hezuo").css({"borderBottom":"2px solid #ed1475","color":"#ed1475"});
		});
		
	});
});